package org.sgy.mall.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.sgy.mall.model.Cart;

public class CartServlet extends HttpServlet {

	public CartServlet() {
		System.out.println("init constructor");
	}

	@Override
	public void init() throws ServletException {
		System.out.println("init");
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// resp.getOutputStream().println("hello servlet");
		resp.setContentType("text/html;charset=UTF-8");
		PrintWriter writer = resp.getWriter();
		writer.println("你好！");
		writer.println("say hi！");
		// resp.getOutputStream().println("你好！");
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		HttpSession session = req.getSession();
		// 接口购物车表单参数
		Map<String, String[]> parameterMap = req.getParameterMap();
		String type = parameterMap.get("type")[0];
		if (type.equals("add")) {
			// 处理添加购物车逻辑
			Cart cart = new Cart();
			cart.setId(Integer.parseInt(parameterMap.get("id")[0]));
			cart.setName(parameterMap.get("name")[0]);
			cart.setPrice(Double.parseDouble(parameterMap.get("price")[0]));
			cart.setNum(Integer.parseInt(parameterMap.get("num")[0]));

			// 从session当中获取购物车信息
			Object cartListObject = session.getAttribute("cartList");
			List<Cart> cartList = null;
			if (cartListObject == null) {
				cartList = new ArrayList<Cart>();
				session.setAttribute("cartList", cartList);
				cartListObject = session.getAttribute("cartList");
			}
			cartList = (ArrayList<Cart>) cartListObject;
			// 判断购物车当中是否有相同商品，如果有则调整数量，否则添加到购物车
			boolean hasCart = false;
			for (Cart cart1 : cartList) {
				if (cart1.getId() == cart.getId()) {
					cart1.setNum(cart1.getNum() + cart.getNum());
					hasCart = true;
					break;
				}
			}
			if (!hasCart) {
				cartList.add(cart);
			}
		}
		resp.sendRedirect("/edmall/product/cartList.jsp");
	}

}
